<template>
  <div class="admin-layout">
    <AdminHeader />
    <div class="main-wrapper">
      <AdminNavbar />
      <div class="content-wrapper">
        <div class="order-list-container">
          <div class="page-header">
            <h2>订单管理</h2>
            <div class="header-actions">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索订单号或产品型号"
                clearable
                class="search-input"
                @clear="handleSearch"
                @keyup.enter="handleSearch"
              >
                <template #suffix>
                  <el-icon class="el-input__icon" @click="handleSearch">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
              <el-select v-model="filterStatus" placeholder="状态筛选" clearable @change="handleSearch">
                <el-option label="待处理" value="待处理" />
                <el-option label="生产中" value="生产中" />
                <el-option label="已完成" value="已完成" />
              </el-select>
              <el-button type="primary" @click="openAddDialog">
                <el-icon><Plus /></el-icon> 添加订单
              </el-button>
            </div>
          </div>

          <!-- 订单列表 -->
          <el-table :data="orders" border style="width: 100%" v-loading="loading">
            <el-table-column prop="orderId" label="订单ID" width="80" />
            <el-table-column prop="productModel" label="产品型号" width="120" />
              <el-table-column prop="colorTemp" label="色温" width="120" />
            <el-table-column prop="quantity" label="订单需求数量" width="100" />
              <el-table-column prop="count" label="有效已生产" width="100" />
              <el-table-column prop="lowcount" label="废弃品" width="100" />
              <el-table-column prop="orderPrice" label="订单价格" width="100" />
              <el-table-column label="所属生产线" width="100">
                  <template #default="scope">
                      {{ getLineName(scope.row.orderBylineId)}}
                  </template>
              </el-table-column>
              <el-table-column label="是否加急" width="100">
                  <template #default="scope">
                  <el-tag :type="getPriority(scope.row.priority)">
                      {{ getPriorityText(scope.row.priority) }}
                  </el-tag>
                  </template>
              </el-table-column>
            <el-table-column label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="customer" label="客户名称" width="150" />
              <el-table-column prop="customerPhone" label="客户联系方式" width="150" />
            <el-table-column label="下单时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.begintime) }}
              </template>
            </el-table-column>
            <el-table-column label="交付时间" width="180">
              <template #default="scope">
                {{ formatDateTime(scope.row.endtime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="300">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  @click="handleEdit(scope.row)"
                  :disabled="scope.row.status === '生产中' || scope.row.status === '已完成'"
                >
                  <el-icon><Edit /></el-icon> 编辑
                </el-button>
                <el-button
                  size="small"
                  type="success"
                  @click="assignProduction"
                  :disabled="scope.row.status === '已完成' || scope.row.status === '已取消' || scope.row.status === '生产中'"
                >
                  <el-icon><Connection /></el-icon> 去分配产线
                </el-button>
                <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(scope.row)"
                  :disabled="scope.row.status === '生产中' || scope.row.status === '已完成'"
                >
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
                <el-button
                  v-if="scope.row.priority === '0'"
                  size="small"
                  type="warning"
                  @click="handleSetUrgent(scope.row)"
                >
                  <el-icon><Star /></el-icon> 设为加急
                </el-button>
                <el-button
                  v-if="scope.row.priority === '1'"
                  size="small"
                  type="info"
                  @click="handleCancelUrgent(scope.row)"
                >
                  <el-icon><StarFilled /></el-icon> 取消加急
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑订单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑订单' : '添加订单'"
      width="500px"
      destroy-on-close
    >
      <el-form :model="orderForm" :rules="rules" ref="orderFormRef" label-width="100px">
        <el-form-item label="产品型号" prop="productModel">
          <el-input v-model="orderForm.productModel" placeholder="请输入产品型号" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="orderForm.quantity" :min="1" :max="100000000" style="width: 100%" />
        </el-form-item>
          <el-form-item label="色温" prop="colorTemp">
              <el-input-number v-model="orderForm.colorTemp" :min="1" :max="100000000" style="width: 100%" />
          </el-form-item>
          <el-form-item label="订单价格" prop="orderPrice">
              <el-input-number v-model="orderForm.orderPrice" :min="1" :max="100000000" style="width: 100%" />
          </el-form-item>
        <el-form-item label="客户名称" prop="customer">
          <el-input v-model="orderForm.customer" placeholder="请输入客户名称" />
        </el-form-item>
          <el-form-item label="客户联系方式" prop="customerPhone">
              <el-input v-model="orderForm.customerPhone" placeholder="请输入客户联系方式" />
          </el-form-item>
        <el-form-item label="订单状态" prop="status">
          <el-select v-model="orderForm.status" placeholder="请选择订单状态" style="width: 100%">
            <el-option label="待排产" value="待排产" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </el-form-item>
        <el-form-item label="交付时间" prop="deliveryDate">
          <el-date-picker
            v-model="orderForm.endtime"
            type="datetime"
            placeholder="选择交付时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="删除确认"
      width="400px"
    >
      <div class="delete-confirm">
        <el-icon class="warning-icon"><Warning /></el-icon>
        <p>确定要删除订单 "{{ currentOrder?.orderNumber }}" 吗？此操作不可恢复。</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
    getProductionOrders,
    addProductionOrder,
    updateProductionOrder,
    searchProductionOrder,
    assignOrderToLine, deleteOrder,
    setPriorityUrgent,
    cancelPriorityUrgent
} from '@/api/production'
import AdminHeader from '@/components/AdminHeader.vue'
import AdminNavbar from '@/components/AdminNavbar.vue'
import { Search, Plus, Edit, Delete, Connection, Warning, Star, StarFilled } from '@element-plus/icons-vue'
import router from "@/router/index.js";

// 数据定义
const orders = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchKeyword = ref('')
const filterStatus = ref('')
const dialogVisible = ref(false)
const deleteDialogVisible = ref(false)
const assignDialogVisible = ref(false)
const isEdit = ref(false)
const currentOrder = ref(null)
const orderFormRef = ref(null)
const assignFormRef = ref(null)

// 表单数据
const orderForm = reactive({
  orderId: null,
  orderNumber: '',
  productModel: '',
  quantity: 1,
  orderPrice:'',
  colorTemp: '',
  customer: '',
  customerPhone:'',
  status: '待处理',
  endtime: null
})

// 分配产线表单数据
const assignForm = reactive({
  lineId: null,
  startTime: new Date(),
  endTime: null
})

// 表单验证规则
const rules = {
  orderNumber: [
    { required: true, message: '请输入订单编号', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  productModel: [
    { required: true, message: '请输入产品型号', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ],
  customerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择订单状态', trigger: 'change' }
  ],
    endtime: [
    { required: true, message: '请选择交付时间', trigger: 'change' }
  ]
}


// 获取订单列表
const fetchOrders = async () => {
  loading.value = true
  try {
    let res;
    const params = {
      current: currentPage.value,
      size: pageSize.value
    };

    // 根据是否有搜索关键字或状态筛选决定调用哪个接口
    if (searchKeyword.value || filterStatus.value) {
      // 使用搜索接口
      res = await searchProductionOrder({
        ...params,
        key: searchKeyword.value,
        status: filterStatus.value
      });
      console.log(res);
    } else {
      // 使用普通分页接口
      res = await getProductionOrders(params);
        console.log(res);
    }

    if (res.success) {
      orders.value = res.data.records || res.data;
      total.value = res.data.total || res.data.length;
    } else {
      ElMessage.error(res.message || '获取订单列表失败');
    }
  } catch (error) {
    console.error('获取订单列表失败:', error);
    ElMessage.error('获取订单列表失败');
  } finally {
    loading.value = false;
  }
}


// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchOrders()
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchOrders()
}

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchOrders()
}

// 打开添加对话框
const openAddDialog = () => {
  isEdit.value = false
  Object.assign(orderForm, {
    orderId: null,
    orderNumber: `ORD-${new Date().getFullYear()}-${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}`,
    productModel: '',
    quantity: 1,
    orderPrice:'',
    customer: '',
    customerPhone:'',
    status: '待排产',
    endtime: null,
  })
  dialogVisible.value = true
}

// 打开编辑对话框
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(orderForm, {
    orderId: row.orderId,
    orderNumber: row.orderNumber,
    productModel: row.productModel,
    quantity: row.quantity,
    customer: row.customer,
    customerPhone:row.customerPhone,
    colorTemp:row.colorTemp,
    orderPrice:row.orderPrice,
    status: row.status,
    endtime: row.endtime ? new Date(row.endtime) : null
  })
  dialogVisible.value = true
}

// 打开分配产线对话框
const assignProduction = () => {
    router.push('/line/free')
};

// 打开删除确认对话框
const handleDelete = (row) => {
  currentOrder.value = row
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!currentOrder.value || !currentOrder.value.orderId) return;

  try {
    const res = await deleteOrder(currentOrder.value.orderId);

    if (res.success) {
      ElMessage.success(`订单 "${currentOrder.value.orderNumber}" 已成功删除`);
      deleteDialogVisible.value = false;
      await fetchOrders();
    } else {
      ElMessage.error(res.message || '删除订单失败');
    }
  } catch (error) {
    console.error('删除订单失败:', error);
    ElMessage.error('删除订单失败');
  }
}

// 提交订单表单
const submitForm = async () => {
  if (!orderFormRef.value) return

  await orderFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res;
        if (isEdit.value) {
          // 编辑订单
          res = await updateProductionOrder(orderForm);
        } else {
          // 添加订单
          res = await addProductionOrder(orderForm);
        }

        if (res.success) {
          const message = isEdit.value ? '编辑' : '添加';
          ElMessage.success(`订单${message}成功`);
          dialogVisible.value = false;
          fetchOrders();
        } else {
          ElMessage.error(res.message || `订单${isEdit.value ? '编辑' : '添加'}失败`);
        }
      } catch (error) {
        console.error(`订单${isEdit.value ? '编辑' : '添加'}失败:`, error);
        ElMessage.error(`订单${isEdit.value ? '编辑' : '添加'}失败`);
      }
    }
  })
}

// 提交分配产线表单
const submitAssign = async () => {
  if (!assignFormRef.value || !currentOrder.value) return;

  await assignFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await assignOrderToLine(currentOrder.value.orderId, assignForm.lineId);

        if (res.success) {
          ElMessage.success(`订单已成功分配到产线 ${assignForm.lineId}`);
          assignDialogVisible.value = false;
          fetchOrders();
        } else {
          ElMessage.error(res.message || '分配产线失败');
        }
      } catch (error) {
        console.error('分配产线失败:', error);
        ElMessage.error('分配产线失败');
      }
    }
  });
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '生产中':
      return 'success'
    case '待排产':
      return 'info'
    case '完成':
          return 'info'
    default:
      return 'info'
  }
}
const getPriority = (status) => {
    switch (status) {
        case "0":
            return 'success'
        default:
            return 'danger'
    }
}
const getPriorityText=(priority) =>{
    switch (priority) {
        case "0":
            return '正常';
        default:
            return '加急中';
    }
}
const getLineName=(orderBylineId)=>{
    if (orderBylineId){
        return orderBylineId+"号生产线"
    }
    return "未指定生产线"
}
// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return ''
  return new Date(datetime).toLocaleString()
}

// 设置订单为加急
const handleSetUrgent = async (row) => {
  try {
    const res = await setPriorityUrgent(row.orderId);
    if (res.success&&res.data!=="订单设置加急失败，无对应空余生产线") {
      ElMessage.success('订单已设置为加急');
      await fetchOrders();
    }
    else if (res.data==="订单设置加急失败，无对应空余非加急生产线") {
        ElMessage.error(res.data);
    }else {
      ElMessage.error(res.message || '设置加急失败');
    }
  } catch (error) {
    console.error('设置加急失败:', error);
    ElMessage.error('设置加急失败');
  }
};

// 取消订单加急
const handleCancelUrgent = async (row) => {
  try {
    const res = await cancelPriorityUrgent(row.orderId);
    if (res.success) {
      ElMessage.success('已取消订单加急状态');
      await fetchOrders();
    } else {
      ElMessage.error(res.message || '取消加急失败');
    }
  } catch (error) {
    console.error('取消加急失败:', error);
    ElMessage.error('取消加急失败');
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7f9;
}

.main-wrapper {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.content-wrapper {
  flex: 1;
  padding: 24px;
  overflow: auto;
  background: #fff;
  margin: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.order-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.order-info {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.delete-confirm {
  display: flex;
  align-items: center;
  gap: 10px;
}

.warning-icon {
  font-size: 24px;
  color: #F56C6C;
}
</style>
